﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GTA.BusinessLogic
{
    public class Configuration
    {
        public BusinessEntity.Configuration.SystemConfiguration GetSystemConfiguration(BusinessEntity.UserManagement.User user)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            BusinessEntity.Configuration.SystemConfiguration systemConfig = ra.GetSystemConfiguration(user);

            if (systemConfig == null)
                throw new System.Configuration.ConfigurationErrorsException("Não foi possível obter as configurações do sistema. Verifique o arquivo de configurações ou reinstale a aplicação.");

            return systemConfig;
        }
        public void SaveSystemConfiguration(BusinessEntity.Configuration.SystemConfiguration systemConfiguration, BusinessEntity.UserManagement.User user)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            ra.SaveSystemConfiguration(systemConfiguration, user);
        }
        public void SaveHolidays(BusinessEntity.Configuration.Holidays holidays)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            BusinessEntity.Configuration.Holidays currentHolidays = GetHolidays();

            BusinessEntity.Configuration.Holidays includeHolidays = GetIncludeHolidays(holidays, currentHolidays);
            BusinessEntity.Configuration.Holidays excludeHolidays = GetExcludeHolidays(holidays, currentHolidays);

            if (includeHolidays != null && includeHolidays.Holiday != null && includeHolidays.Holiday.Count > 0)
                ra.SaveHolidays(includeHolidays);
            if (excludeHolidays != null && excludeHolidays.Holiday != null && excludeHolidays.Holiday.Count > 0)
                ra.DeleteHolidays(excludeHolidays);
        }
        private BusinessEntity.Configuration.Holidays GetExcludeHolidays(BusinessEntity.Configuration.Holidays holidays, BusinessEntity.Configuration.Holidays currentHolidays)
        {
            BusinessEntity.Configuration.Holidays result = new BusinessEntity.Configuration.Holidays();
            if (currentHolidays != null && currentHolidays.Holiday != null && holidays != null && holidays.Holiday != null)
                result.Holiday.AddRange(currentHolidays.Holiday.FindAll(it => holidays.Holiday.Find(it2 => it2.Date.CompareTo(it.Date) == 0) == DateTime.MinValue));
            return result;
        }
        private BusinessEntity.Configuration.Holidays GetIncludeHolidays(BusinessEntity.Configuration.Holidays holidays, BusinessEntity.Configuration.Holidays currentHolidays)
        {
            BusinessEntity.Configuration.Holidays result = new BusinessEntity.Configuration.Holidays();
            if (holidays != null && holidays.Holiday != null)
                result.Holiday.AddRange(
                        holidays.Holiday.FindAll(it => currentHolidays == null || currentHolidays.Holiday == null || currentHolidays.Holiday.Find(it2 => it2.Date.CompareTo(it.Date) == 0) == DateTime.MinValue)
                    );
            return result;
        }
        public BusinessEntity.Configuration.Holidays GetHolidays()
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            return ra.GetHolidays();
        }
        public List<BusinessEntity.Configuration.Alert> ListAlerts(BusinessEntity.UserManagement.User user, BusinessEntity.Configuration.AlertFilter filter)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            return ra.ListAlerts(user, filter);
        }
        public void SaveAlert(BusinessEntity.Configuration.Alert alert, BusinessEntity.UserManagement.User user)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            try
            {

                ra.StartTransaction();

                if (alert.ID == 0 || alert.ID == Int32.MinValue)
                {
                    alert.ID = ra.SaveAlert(alert, user);
                    SaveAlertReferences(alert, ra);
                }
                else
                {
                    ra.UpdateAlert(alert);
                    ra.CleanAlertReferences(alert.ID);
                    SaveAlertReferences(alert, ra);
                }

                ra.CommitTransaction();
            }
            catch (Exception ex)
            {
                ra.RollBackTransaction();
                throw ex;
            }
        }
        private void SaveAlertReferences(BusinessEntity.Configuration.Alert alert, ResourceAccess.Configuration ra)
        {
            alert.AlertNotificationTypeList.ForEach(it => ra.SaveAlertNotificationTypes(alert.ID, it));
            if (alert is BusinessEntity.Configuration.AlertTasks)
            {
                Int32 alertTaskID = ra.SaveAlertTasks(alert.ID, alert as BusinessEntity.Configuration.AlertTasks);
                if (((BusinessEntity.Configuration.AlertTasks)alert).Projects != null && ((BusinessEntity.Configuration.AlertTasks)alert).Projects.Count > 0)
                    ((BusinessEntity.Configuration.AlertTasks)alert).Projects.ForEach(it => ra.SaveAlertTasksProjects(alertTaskID, it));
                if (((BusinessEntity.Configuration.AlertTasks)alert).Users != null && ((BusinessEntity.Configuration.AlertTasks)alert).Users.Count > 0)
                    ((BusinessEntity.Configuration.AlertTasks)alert).Users.ForEach(it => ra.SaveAlertTasksUsers(alertTaskID, it));
                if (((BusinessEntity.Configuration.AlertTasks)alert).Categories != null && ((BusinessEntity.Configuration.AlertTasks)alert).Categories.Count > 0)
                    ((BusinessEntity.Configuration.AlertTasks)alert).Categories.ForEach(it => ra.SaveAlertTasksCategories(alertTaskID, it));
                if (((BusinessEntity.Configuration.AlertTasks)alert).States != null && ((BusinessEntity.Configuration.AlertTasks)alert).States.Count > 0)
                    ((BusinessEntity.Configuration.AlertTasks)alert).States.ForEach(it => ra.SaveAlertTasksStates(alertTaskID, it));
                if (alert is BusinessEntity.Configuration.AlertTasksHistoryExcedTask)
                    ra.SaveAlertTasksHistoryExcedTask(alertTaskID, alert as BusinessEntity.Configuration.AlertTasksHistoryExcedTask);
                else if (alert is BusinessEntity.Configuration.AlertTasksOverdueAlert)
                    ra.SaveAlertTasksOverdueAlert(alertTaskID, alert as BusinessEntity.Configuration.AlertTasksOverdueAlert);
            }
        }
        public BusinessEntity.Configuration.Alert GetAlert(BusinessEntity.Configuration.Alert alertEdit)
        {
            BusinessEntity.Configuration.Alert alert = null;
            switch (alertEdit.Type)
            {
                case BusinessEntity.Configuration.AlertType.AlertTaskHistoryExcedTask:
                    alert = GetAlertTasksHistoryExcedTask(alertEdit.ID);
                    break;
                case BusinessEntity.Configuration.AlertType.AlertTaskOverdue:
                    alert = GetAlertTasksOverdueAlert(alertEdit.ID);
                    break;
            }
            return alert;
        }
        private BusinessEntity.Configuration.AlertTasksHistoryExcedTask GetAlertTasksHistoryExcedTask(Int32 alertID)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            return ra.GetAlertTasksHistoryExcedTask(alertID);
        }
        private BusinessEntity.Configuration.AlertTasksOverdueAlert GetAlertTasksOverdueAlert(Int32 alertID)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            return ra.GetAlertTasksOverdueAlert(alertID);
        }
        public void DeleteAlert(int alertID)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            ra.DeleteAlert(alertID);
        }
        public void UpdateAlertState(int alertID, BusinessEntity.Configuration.AlertState notificationState)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            ra.UpdateAlertState(alertID, notificationState);
        }
        public String GetAlertsToolTipTextDescription(List<BusinessEntity.Configuration.Alert> alerts, BusinessEntity.UserManagement.User loggedUser)
        {
            StringBuilder description = new StringBuilder();
            if (alerts != null && alerts.Count > 0)
            {
                foreach (BusinessEntity.Configuration.Alert itemAlert in alerts)
                    description.Append(GetAlertsTextDescription(itemAlert, loggedUser));
            }
            return description.ToString();
        }
        public String GetAlertsTextDescription(BusinessEntity.Configuration.Alert itemAlert, BusinessEntity.UserManagement.User loggedUser)
        {
            StringBuilder description = new StringBuilder();
            BusinessEntity.Configuration.Alert alert = GetAlert(itemAlert);
            if (alert is BusinessEntity.Configuration.AlertTasks)
                description.Append(GetAlertTasksDescription(alert as BusinessEntity.Configuration.AlertTasks, loggedUser));
            return description.ToString();
        }
        private String GetAlertTasksDescription(BusinessEntity.Configuration.AlertTasks itemAlertTask, BusinessEntity.UserManagement.User loggedUser)
        {
            StringBuilder description = new StringBuilder();

            BusinessEntity.TaskFilter taskFilter = new BusinessEntity.TaskFilter();
            taskFilter.Category = itemAlertTask.Categories;
            taskFilter.DesignedTo = itemAlertTask.Users;
            taskFilter.Project = itemAlertTask.Projects;
            taskFilter.State = itemAlertTask.States;
            taskFilter.ScheduleEstimatedEndFrom = itemAlertTask.ScheduleEndFrom;
            taskFilter.ScheduleEstimatedEndTo = itemAlertTask.ScheduleEndTo;
            taskFilter.ScheduleEstimatedStartFrom = itemAlertTask.ScheduleStartFrom;
            taskFilter.ScheduleEstimatedStartTo = itemAlertTask.ScheduleStartTo;

            BusinessLogic.GTA bl = new BusinessLogic.GTA();
            List<BusinessEntity.Task> tasks = bl.ListArchitectureTasks(taskFilter, loggedUser);

            if (tasks != null && tasks.Count > 0)
            {
                StringBuilder tasksListDescription = new StringBuilder();

                if (itemAlertTask is BusinessEntity.Configuration.AlertTasksHistoryExcedTask)
                    tasksListDescription.Append(GetAlertTasksHistoryExcedTaskDescription(itemAlertTask as BusinessEntity.Configuration.AlertTasksHistoryExcedTask, tasks, loggedUser));
                else if (itemAlertTask is BusinessEntity.Configuration.AlertTasksOverdueAlert)
                    tasksListDescription.Append(GetAlertTasksOverdueAlertDescription(itemAlertTask as BusinessEntity.Configuration.AlertTasksOverdueAlert, tasks));

                if (!String.IsNullOrEmpty(tasksListDescription.ToString()))
                {
                    description.Append("Alerta de Tarefas\r\n\r\n");
                    description.Append(tasksListDescription.ToString());
                }
            }

            return description.ToString();
        }
        private String GetAlertTasksHistoryExcedTaskDescription(BusinessEntity.Configuration.AlertTasksHistoryExcedTask itemAlert, List<BusinessEntity.Task> tasks, BusinessEntity.UserManagement.User loggedUser)
        {
            StringBuilder description = new StringBuilder();
            StringBuilder tasksListDescription = new StringBuilder();

            BusinessEntity.Configuration.Holidays holidays = GetHolidays();
            BusinessLogic.GTA bl = new BusinessLogic.GTA();
            foreach (BusinessEntity.Task itemTask in tasks)
            {
                if (QualifyAlertTaskHistoryExcedTask(itemAlert, itemTask, holidays, loggedUser))
                    tasksListDescription.Append(GetTaskDescription(itemTask));
            }

            if (!String.IsNullOrEmpty(tasksListDescription.ToString()))
            {
                description.Append("Tarefas que o tempo de interrupção supera o tempo da tarefa:\r\n");
                description.Append(tasksListDescription.ToString());
            }

            return description.ToString();
        }
        private List<BusinessEntity.Task> GetTasksStartAlert(BusinessEntity.Configuration.AlertTasksOverdueAlert itemAlert, List<BusinessEntity.Task> tasks)
        {
            List<BusinessEntity.Task> result = null;
            if (itemAlert.StartOverdueAlert &&
                itemAlert.StartOverdueDays != 0 &&
                itemAlert.StartOverdueDays != Int32.MinValue)
                result = tasks.FindAll(it => it.ScheduleRealizedStart == DateTime.MinValue &&
                                    DateTime.Now.Date.CompareTo(it.ScheduleEstimatedStart.Date.AddDays(itemAlert.StartOverdueDays * -1)) >= 0);

            return result;
        }
        private List<BusinessEntity.Task> GetTasksEndAlert(BusinessEntity.Configuration.AlertTasksOverdueAlert itemAlert, List<BusinessEntity.Task> tasks)
        {
            List<BusinessEntity.Task> result = new List<global::GTA.BusinessEntity.Task>();
            if (itemAlert.EndOverdueAlert)
            {
                if (itemAlert.EndOverdueDays != 0 &&
                    itemAlert.EndOverdueDays != Int32.MinValue)
                    result = tasks.FindAll(it => it.ScheduleRealizedEnd == DateTime.MinValue &&
                                                 DateTime.Now.Date.CompareTo(it.ScheduleEstimatedEnd.Date.AddDays(itemAlert.EndOverdueDays * -1)) >= 0);
                else
                    if (itemAlert.EndOverduePercent != 0 &&
                        itemAlert.EndOverduePercent != Int32.MinValue)
                    {
                        foreach (BusinessEntity.Task itemTask in tasks)
                        {
                            if (itemTask.ScheduleEstimatedEnd.Date.Subtract(itemTask.ScheduleEstimatedStart.Date).Days > 0)
                            {
                                if (itemTask.ScheduleRealizedEnd == DateTime.MinValue &&
                                    DateTime.Now.Date.CompareTo(itemTask.ScheduleEstimatedStart.Date) >= 0 &&
                                    ((DateTime.Now.Date.Subtract(itemTask.ScheduleEstimatedStart.Date).Days * 100) / itemTask.ScheduleEstimatedEnd.Date.Subtract(itemTask.ScheduleEstimatedStart.Date).Days) >= itemAlert.EndOverduePercent)
                                    result.Add(itemTask);
                            }
                            else
                            {
                                if (itemTask.ScheduleRealizedEnd == DateTime.MinValue &&
                                    DateTime.Now.Date.CompareTo(itemTask.ScheduleEstimatedStart.Date) >= 0)
                                    result.Add(itemTask);
                            }
                        }
                    }
            }
            return result;
        }
        private String GetAlertTasksOverdueAlertDescription(BusinessEntity.Configuration.AlertTasksOverdueAlert itemAlert, List<BusinessEntity.Task> tasks)
        {
            StringBuilder description = new StringBuilder();

            List<BusinessEntity.Task> resultTasksStartAlert = GetTasksStartAlert(itemAlert as BusinessEntity.Configuration.AlertTasksOverdueAlert, tasks);
            if (resultTasksStartAlert != null && resultTasksStartAlert.Count > 0)
            {
                description.Append("Tarefas com alerta de atraso para início:\r\n");
                resultTasksStartAlert.ForEach(it => description.Append(GetTaskDescription(it)));
                description.Append("\r\n");
            }

            List<BusinessEntity.Task> resultTasksEndAlert = GetTasksEndAlert(itemAlert as BusinessEntity.Configuration.AlertTasksOverdueAlert, tasks);
            if (resultTasksEndAlert != null && resultTasksEndAlert.Count > 0)
            {
                description.Append("Tarefas com alerta de atraso para entrega:\r\n");
                resultTasksEndAlert.ForEach(it => description.Append(GetTaskDescription(it)));
                description.Append("\r\n");
            }

            return description.ToString();
        }
        private String GetTaskDescription(BusinessEntity.Task itemTask)
        {
            StringBuilder description = new StringBuilder();
            description.Append(itemTask.ID.ToString());
            description.Append(" - ");
            description.Append(itemTask.ScheduleEstimatedStart.ToString("dd/MM/yyyy"));
            description.Append(" - ");
            description.Append(itemTask.ScheduleEstimatedEnd.ToString("dd/MM/yyyy"));
            description.Append(" - ");
            description.Append(itemTask.Title);
            description.Append("\r\n");
            return description.ToString();
        }
        public void UpdateAlertSleep(int alertID, BusinessEntity.Configuration.AlertSleepType alertSleepType)
        {
            DateTime sleepDate = DateTime.Now;
            switch (alertSleepType)
            {
                case BusinessEntity.Configuration.AlertSleepType.FiveMinutes:
                    sleepDate = sleepDate.AddMinutes(5);
                    break;
                case BusinessEntity.Configuration.AlertSleepType.TenMinutes:
                    sleepDate = sleepDate.AddMinutes(10);
                    break;
                case BusinessEntity.Configuration.AlertSleepType.FifteenMinutes:
                    sleepDate = sleepDate.AddMinutes(15);
                    break;
                case BusinessEntity.Configuration.AlertSleepType.ThirtyMinutes:
                    sleepDate = sleepDate.AddMinutes(30);
                    break;
                case BusinessEntity.Configuration.AlertSleepType.OneHour:
                    sleepDate = sleepDate.AddHours(1);
                    break;
                case BusinessEntity.Configuration.AlertSleepType.OneDay:
                    sleepDate = sleepDate.AddDays(1);
                    break;
                case BusinessEntity.Configuration.AlertSleepType.None:
                    sleepDate = DateTime.MinValue;
                    break;
                default:
                    sleepDate = DateTime.MinValue;
                    break;
            }
            UpdateAlertSleep(alertID, sleepDate);
        }
        public void UpdateAlertSleep(Int32 alertID, DateTime sleepDate)
        {
            ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
            ra.UpdateAlertSleep(alertID, sleepDate);
        }
        public List<BusinessEntity.Configuration.Alert> FillAlertsDescription(List<BusinessEntity.Configuration.Alert> alerts, BusinessEntity.UserManagement.User loggedUser)
        {
            if (alerts != null && alerts.Count > 0)
            {
                foreach (BusinessEntity.Configuration.Alert itemAlert in alerts)
                    itemAlert.Description = GetAlertsTextDescription(itemAlert, loggedUser);
            }
            return alerts;
        }
        private bool QualifyAlertTaskHistoryExcedTask(BusinessEntity.Configuration.Alert itemAlert, BusinessEntity.Task itemTask, BusinessEntity.Configuration.Holidays holidays, BusinessEntity.UserManagement.User loggedUser)
        {
            bool excedTaskTime = false;

            BusinessLogic.GTA bl = new GTA();
            itemTask.UserHistory = bl.ListTaskHistory(loggedUser, itemTask);

            //Define the total time of the included Interruption Histories.
            TimeSpan totalHistoryTime = new TimeSpan();
            if (itemTask.UserHistory != null && itemTask.UserHistory.Count > 0)
            {
                foreach (BusinessEntity.TaskHistory itemHistory in itemTask.UserHistory)
                    totalHistoryTime = totalHistoryTime.Add(bl.GetTaskHistoryTotalTime(itemHistory));
            }

            //Define the total time of the task period.
            TimeSpan totalTaskTime = new TimeSpan();
            if (itemTask.ScheduleEstimatedEnd.Date.CompareTo(itemTask.ScheduleEstimatedStart.Date) == 0)
            {
                bool holiday = holidays != null &&
                               holidays.Holiday != null &&
                               holidays.Holiday.Count > 0 &&
                               holidays.Holiday.Exists(it => it.Date.CompareTo(itemTask.ScheduleEstimatedStart.Date) == 0) ? true : false;
                bool weekend = itemTask.ScheduleEstimatedEnd.DayOfWeek == DayOfWeek.Saturday ||
                               itemTask.ScheduleEstimatedEnd.DayOfWeek == DayOfWeek.Sunday;

                bool shouldCount = true;

                if ((!((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).Holidays && holiday) ||
                     !((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).WeekEnd && weekend)
                    shouldCount = false;

                if (shouldCount)
                {
                    totalTaskTime = totalTaskTime.Add(itemTask.ScheduleEstimatedEnd.Subtract(itemTask.ScheduleEstimatedStart));
                    if (((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).HoursDay != 0 &&
                        ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).HoursDay != Int32.MinValue &&
                        totalTaskTime.Hours > ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).HoursDay)
                        totalTaskTime = new TimeSpan(((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).HoursDay, 0, 0);
                }
            }
            else
            {
                Int32 qtdDays = itemTask.ScheduleEstimatedEnd.Date.Subtract(itemTask.ScheduleEstimatedStart.Date).Days;
                Int32 qtdValidDays = 0;

                for (int i = 0; i < qtdDays; i++)
                {
                    bool weekend = false;
                    bool holiday = false;
                    bool shouldCount = true;

                    if (itemTask.ScheduleEstimatedStart.AddDays(i).DayOfWeek == DayOfWeek.Saturday ||
                        itemTask.ScheduleEstimatedStart.AddDays(i).DayOfWeek == DayOfWeek.Sunday)
                        weekend = true;

                    if (holidays != null && holidays.Holiday != null && holidays.Holiday.Count > 0 &&
                        holidays.Holiday.Exists(it => it.Date.CompareTo(itemTask.ScheduleEstimatedStart.AddDays(i).Date) == 0))
                        holiday = true;

                    if ((!((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).Holidays && holiday) ||
                         !((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).WeekEnd && weekend)
                        shouldCount = false;

                    if (shouldCount)
                        qtdValidDays++;
                }

                if (((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).HoursDay != 0 &&
                    ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).HoursDay != Int32.MinValue)
                    totalTaskTime = new TimeSpan(qtdValidDays * ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).HoursDay, 0, 0);
                else
                    totalTaskTime = new TimeSpan(qtdValidDays * 24, 0, 0);
            }

            //If the Total and History time has value and are higher than the task time, include the task on the alert.
            if (totalTaskTime.TotalMinutes > 0 &&
                totalHistoryTime.TotalMinutes > 0)
            {
                if (((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).Percent != 0 &&
                    ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).Percent != Int32.MinValue)
                {
                    double percent = (totalHistoryTime.TotalMinutes * 100) / totalTaskTime.TotalMinutes;
                    if (Convert.ToInt32(percent) >= ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)itemAlert).Percent + 100)
                        excedTaskTime = true;
                }
                else
                {
                    if (totalHistoryTime.CompareTo(totalTaskTime) > 0)
                        excedTaskTime = true;
                }
            }

            return excedTaskTime;
        }
        public void SendAlertsByEMail(List<BusinessEntity.Configuration.Alert> alerts, BusinessEntity.UserManagement.User user)
        {
            if (!String.IsNullOrEmpty(user.EMailAddress) && alerts != null && alerts.Count > 0)
            {
                String alertsList = GetAlertsListHtmlFormat(alerts, user);

                if (!String.IsNullOrEmpty(alertsList))
                {
                    ResourceAccess.Configuration ra = new ResourceAccess.Configuration();
                    String subject = "GTA - Alerta";
                    String alertEMailTemplate = BusinessLogic.Properties.Resources.TemplateAlertEMail;
                    String message = alertEMailTemplate.Replace("[alerts_list]", alertsList);
                    ra.SendMicrosoftOutLookEMail(subject, message, new String[] { user.EMailAddress });
                }
            }
        }
        public String GetAlertsListHtmlFormat(List<BusinessEntity.Configuration.Alert> alerts, BusinessEntity.UserManagement.User loggedUser)
        {
            StringBuilder htmlResult = new StringBuilder();
            if (alerts != null && alerts.Count > 0)
            {
                foreach (BusinessEntity.Configuration.Alert itemAlert in alerts)
                {
                    htmlResult.Append(GetAlertHtmlFormat(itemAlert, loggedUser));
                    if (!String.IsNullOrEmpty(htmlResult.ToString()))
                        htmlResult.Append("<br/>");
                }
            }
            return htmlResult.ToString();
        }
        private String GetAlertHtmlFormat(BusinessEntity.Configuration.Alert itemAlert, BusinessEntity.UserManagement.User loggedUser)
        {
            String htmlResult = String.Empty;
            BusinessEntity.Configuration.Alert alert = GetAlert(itemAlert);
            if (alert is BusinessEntity.Configuration.AlertTasks)
                htmlResult = GetAlertTasksHtmlFormat(alert as BusinessEntity.Configuration.AlertTasks, loggedUser);
            return htmlResult;
        }
        private String GetAlertTasksHtmlFormat(BusinessEntity.Configuration.AlertTasks itemAlertTask, BusinessEntity.UserManagement.User loggedUser)
        {
            StringBuilder description = new StringBuilder();

            BusinessEntity.TaskFilter taskFilter = new BusinessEntity.TaskFilter();
            taskFilter.Category = itemAlertTask.Categories;
            taskFilter.DesignedTo = itemAlertTask.Users;
            taskFilter.Project = itemAlertTask.Projects;
            taskFilter.State = itemAlertTask.States;
            taskFilter.ScheduleEstimatedEndFrom = itemAlertTask.ScheduleEndFrom;
            taskFilter.ScheduleEstimatedEndTo = itemAlertTask.ScheduleEndTo;
            taskFilter.ScheduleEstimatedStartFrom = itemAlertTask.ScheduleStartFrom;
            taskFilter.ScheduleEstimatedStartTo = itemAlertTask.ScheduleStartTo;

            BusinessLogic.GTA bl = new BusinessLogic.GTA();
            List<BusinessEntity.Task> tasks = bl.ListArchitectureTasks(taskFilter, loggedUser);

            if (tasks != null && tasks.Count > 0)
            {
                if (itemAlertTask is BusinessEntity.Configuration.AlertTasksHistoryExcedTask)
                    description.Append(GetAlertTasksHistoryExcedTaskHtmlFormat(itemAlertTask as BusinessEntity.Configuration.AlertTasksHistoryExcedTask, tasks, loggedUser));
                else if (itemAlertTask is BusinessEntity.Configuration.AlertTasksOverdueAlert)
                    description.Append(GetAlertTasksOverdueAlertHtmlFormat(itemAlertTask as BusinessEntity.Configuration.AlertTasksOverdueAlert, tasks));
            }

            return description.ToString();
        }
        private String GetAlertTasksHistoryExcedTaskHtmlFormat(BusinessEntity.Configuration.AlertTasksHistoryExcedTask itemAlert, List<BusinessEntity.Task> tasks, BusinessEntity.UserManagement.User loggedUser)
        {
            String resultHtml = String.Empty;

            BusinessEntity.Configuration.Holidays holidays = GetHolidays();
            for (Int32 i = 0; i < tasks.Count; i++)
            {
                if (!QualifyAlertTaskHistoryExcedTask(itemAlert, tasks[i], holidays, loggedUser))
                {
                    tasks.RemoveAt(i);
                    i--;
                }
            }

            if (tasks.Count > 0)
            {
                BusinessLogic.GTA bl = new GTA();
                String tasksListDescription = bl.GetTasksListAlertHTMLFormat(tasks);
                if (!String.IsNullOrEmpty(tasksListDescription))
                {
                    resultHtml = BusinessLogic.Properties.Resources.TemplateAlertTasksHistoryExcedTask;
                    resultHtml = resultHtml.Replace("[nome_alerta]", itemAlert.Name);
                    resultHtml = resultHtml.Replace("[task_list]", tasksListDescription);
                }
            }

            return resultHtml;
        }
        private String GetAlertTasksOverdueAlertHtmlFormat(BusinessEntity.Configuration.AlertTasksOverdueAlert itemAlert, List<BusinessEntity.Task> tasks)
        {
            String resultHtml = String.Empty;

            String template = BusinessLogic.Properties.Resources.TemplateAlertTasksOverdueAlert;
            template = template.Replace("[nome_alerta]", itemAlert.Name);

            String tasksHtmlStartOverdue = String.Empty;
            String tasksHtmlEndOverdue = String.Empty;

            BusinessLogic.GTA bl = new GTA();

            List<BusinessEntity.Task> resultTasksStartAlert = GetTasksStartAlert(itemAlert as BusinessEntity.Configuration.AlertTasksOverdueAlert, tasks);
            tasksHtmlStartOverdue = bl.GetTasksListAlertHTMLFormat(resultTasksStartAlert);

            List<BusinessEntity.Task> resultTasksEndAlert = GetTasksEndAlert(itemAlert as BusinessEntity.Configuration.AlertTasksOverdueAlert, tasks);
            tasksHtmlEndOverdue = bl.GetTasksListAlertHTMLFormat(resultTasksEndAlert);

            if (!String.IsNullOrEmpty(tasksHtmlEndOverdue) ||
                !String.IsNullOrEmpty(tasksHtmlStartOverdue))
            {
                template = template.Replace("[task_list_start]", tasksHtmlStartOverdue);
                template = template.Replace("[task_list_end]", tasksHtmlEndOverdue);
                resultHtml = template;
            }

            return resultHtml;
        }


    }
}
